//
//  NetWorkTools.swift
//  weiboxiangmu
//
//  Created by wei_jingyun on 15/6/28.
//  Copyright © 2015年 wei_jingyun. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

/// 网络访问单独抽一个单例出来，用于管理，后期更换框架，改动较小
class NetWorkTools: AFHTTPSessionManager {
    private static let instance : NetWorkTools = {
        // 设置baseURL 必须以 / 结尾
        let urlString = "https://api.weibo.com/"
        let basURL = NSURL(string: urlString)
        let tools = NetWorkTools(baseURL: basURL)
        // AFURLResponseSerialization.m 解析以服务器传输的 格式来辨别，有时需要自行添加
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as! Set<String>
        return tools
    }()

    // 全局访问的入口
    class func sharedNetWorkTools() -> NetWorkTools {
        return instance
    }
    
    

    // MARK: 发布微博
    /// 发布文本微博
    func postStatus(text : String , finished : (error : NSError?) -> ()){
        if sharedUserAccount?.access_token == nil{
            return // 判断token是否存在
        }
        let urlString = "2/statuses/update.json"
        let params = ["access_token": sharedUserAccount!.access_token,
            "status": text]
        POST(urlString, parameters: params, success: { (_, _) -> Void in
            finished(error: nil)
            }) { [unowned self] (_, error) -> Void in
                Debug.Log(NSThread.currentThread())
                self.showError()
                finished(error: error)
        }
        
    }
    
    func showError(){
        SVProgressHUD.showInfoWithStatus("您的网络不给力或服务器拒绝访问", maskType: SVProgressHUDMaskType.Black)
    }
        
    func show(){
        SVProgressHUD.showWithMaskType(SVProgressHUDMaskType.Black)
    }
        
    func showLogin(){
        SVProgressHUD.showInfoWithStatus("请先登录", maskType: SVProgressHUDMaskType.Black)
    }
    
    func showTextLong(){
        SVProgressHUD.showInfoWithStatus("文字内容过长", maskType: SVProgressHUDMaskType.Black)
    }

}